<template>
  <div style="display: inline-block;margin-left: 10px;">
    <el-button type="warning" size="small" plain @click="handleClickDialog">任务列表</el-button>
    <el-dialog
      title="任务列表"
      :visible.sync="campaignTasksDialog"
      :close-on-click-modal="false"
      :modal-append-to-body="false"
      :append-to-body="true"
      width="70%">
      <el-tabs v-model="activeName">
        <el-tab-pane label="任务列表" name="first">
          <div class="curd-table">
            <div class="table-body">
              <el-table
                v-loading="loading"
                :data="data"
                border
                :header-cell-style="iHeaderCellStyle"
                style="width: 100%">
                <el-table-column
                  prop="name"
                  label="广告系列名称"
                  :show-overflow-tooltip='true'>
                </el-table-column>
                <el-table-column
                  prop="status"
                  label="状态"
                  width="60">
                  <template v-slot="{row}">
                    {{ transferStatus(row.status) }}
                  </template>
                </el-table-column>
                <el-table-column
                  :formatter='formatter'
                  prop="campaignNum"
                  label="广告系列数量"
                  width="95"
                >
                </el-table-column>
                <el-table-column
                  :formatter='formatter'
                  prop="adgroupNumber"
                  label="广告组数量"
                  width="90">
                </el-table-column>
                <el-table-column
                  :formatter='formatter'
                  prop="adNumber"
                  label="广告数量"
                  width="80">
                </el-table-column>
                <el-table-column
                  prop="createUser"
                  label="创建人"
                  width="80">
                  <template v-slot="{row}">
                    {{ transferUser(row.createUser) }}
                  </template>
                </el-table-column>
                <el-table-column
                  prop="updateTime"
                  label="修改时间"
                  width="130"
                  :show-overflow-tooltip='true'>
                </el-table-column>
                <el-table-column
                  label="操作"
                  width="170">
                  <template v-slot="{row}">
                    <template v-if="row.status === 2">
                      <el-button v-show="row.sourceData" size="mini" @click="$emit('click-edit', row, 'copy')">复制</el-button>
                    </template>
                    <template v-else-if="row.status === 3 || row.status === 0">
                      <el-button v-show="row.sourceData" size="mini" @click="$emit('click-edit', row, 'edit')">编辑</el-button>
                    </template>
                    <el-button v-show="row.sourceData" size="mini" @click="showSaveTemplateDialiog(row)">保存模板</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div class="bottom-page clearfix">
              <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="page.currentPage"
                :page-sizes="[10, 20, 30, 40, 50, 100]"
                :page-size="page.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
              </el-pagination>
            </div>
          </div>
          <el-dialog
            width="30%"
            title="任务添加为模板"
            :visible.sync="templateDialog"
            :close-on-click-modal="false"
            append-to-body
            @close="closeTemplateDialog">
            <el-form :model="templateForm" ref="templateForm" label-width="80px">
              <el-form-item
                prop="name"
                label="模板名称"
                :rules="[{ required: true, message: '名称不能为空',trigger: 'blur'}]">
                <el-input v-model="templateForm.name" style="width: 100%"></el-input>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="templateDialog = false">取 消</el-button>
              <el-button type="primary" @click="submitTemplate">确 定</el-button>
            </span>
          </el-dialog>
        </el-tab-pane>
        <el-tab-pane label="任务模板" name="second">
          <div class="curd-table">
            <el-form :inline="true" :model="queryTempForm" size="mini" ref="queryTempForm">
              <el-form-item label="账户ID">
                <el-input v-model="queryTempForm.accountId"></el-input>
              </el-form-item>
              <el-form-item label="名称">
                <el-input v-model="queryTempForm.name"></el-input>
              </el-form-item>
              <el-form-item label="广告类型">
                <el-select v-model="queryTempForm.adType" multiple>
                  <el-option v-for="item in adTypeList"
                             :key="item.value"
                             :label="item.label"
                             :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="操作系统">
                <el-select v-model="queryTempForm.os">
                  <el-option label="Android" value="1"></el-option>
                  <el-option label="iOS" value="2"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="getTemplateData">查询</el-button>
              </el-form-item>
            </el-form>
            <div class="table-body">
              <el-table
                v-loading="loading"
                :data="templateData"
                border
                :header-cell-style="iHeaderCellStyle"
                style="width: 100%">
                <el-table-column
                  prop="accountId"
                  label="账户ID"
                  :show-overflow-tooltip='true'>
                </el-table-column>
                <el-table-column
                  :formatter='formatter'
                  prop="name"
                  label="名称">
                </el-table-column>
                <el-table-column
                  :formatter='formatter'
                  prop="adTypes"
                  label="广告类型">
                </el-table-column>
                <el-table-column
                  :formatter="formatterOs"
                  prop="os"
                  label="操作系统">
                </el-table-column>
                <el-table-column
                  label="操作"
                  width="170">
                  <template v-slot="{row}">
                    <el-button size="mini" @click="$emit('click-edit', row, 'copy')">创建</el-button>
                    <el-button type="warning" size="mini" @click="delTemplate(row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <!--<div class="bottom-page clearfix">-->
            <!--  <el-pagination-->
            <!--    @size-change="handleSizeChange"-->
            <!--    @current-change="handleCurrentChange"-->
            <!--    :current-page="templatePage.currentPage"-->
            <!--    :page-sizes="[10, 20, 30, 40, 50, 100]"-->
            <!--    :page-size="templatePage.pageSize"-->
            <!--    layout="total, sizes, prev, pager, next, jumper"-->
            <!--    :total="templateTotal">-->
            <!--  </el-pagination>-->
            <!--</div>-->
          </div>
        </el-tab-pane>
      </el-tabs>
      <span slot="footer" class="dialog-footer">
              <el-button @click="campaignTasksDialog = false">取 消</el-button>
              <el-button type="primary" @click="campaignTasksDialog = false">确 定</el-button>
            </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  createTiktokCampaignTemplate,
  getCampaignTaskPage,
  getTiktokCampaignTemplateList, removeTiktokCampaignTemplateList
} from "@/api/campaign-management/campaign-management";
import {getAllUser} from "@/api/user";

export default {
  name: "CampaignTasks",
  props: {
    offerId: {
      required: true
    }
  },
  data() {
    return {
      loading: false,
      data: [],
      page: {
        current: 1,
        size: 10,
      },
      total: 0,
      statusList: [
        {value: 0, label: '草稿'},
        {value: 1, label: '创建中'},
        {value: 2, label: '成功'},
        {value: 3, label: '部分成功'},
        {value: 4, label: '失败'}
      ],
      userList: [],
      campaignTasksDialog: false,
      activeName: 'first',
      templateDialog: false,
      templateForm: {
        name: ''
      },
      templateData: [],
      templatePage: {
        current: 1,
        size: 10,
      },
      templateTotal: 0,
      sourceData: null,
      queryTempForm: {
        accountId: '',
        adType: [],
        name: '',
        os: ''
      },
      adTypeList: [
        {label: 'MAI', value: 'MAI'},
        {label: 'ACO', value: 'ACO'},
        {label: 'APPO', value: 'APPO'},
        {label: 'RO', value: 'RO'},
        {label: 'VEO', value: 'VEO'}
      ]
    }
  },
  created() {
    getAllUser({statusList: '0,1,2'}).then(res => {
      this.userList = res.data.data
    });
    this.getTemplateData()
  },
  computed: {
    formatQueryform() {
      return {
        accountId: this.queryTempForm.accountId,
        adType: this.queryTempForm.adType.join(','),
        name: this.queryTempForm.name,
        os: this.queryTempForm.os
      }
    }
  },
  methods: {
    iHeaderCellStyle() {
      return {
        color: '#101010',
        backgroundColor: '#F2F2F2'
      }
    },
    handleSizeChange(val) {
      this.page.size = val
      this.getData()
    },
    handleCurrentChange(val) {
      this.page.current = val
      this.getData()
    },
    async getData() {
      this.loading = true
      const {data: res} = await getCampaignTaskPage({
        ...this.page,
        offerId: this.offerId
      }).finally(() => {
        this.loading = false
      })
      this.total = res.data.total
      this.data = res.data.records
    },
    transferStatus(status) {
      return this.statusList.find(item => item.value === status)['label']
    },
    transferUser(userId) {
      try {
        return this.userList.find(item => item.id === userId)['realName']
      } catch (e) {
        return ''
      }

    },
    formatter(row, column, cellValue, index) {
      if (cellValue == null) {
        return '0'
      }
      return cellValue;
    },
    formatterOs(row, column, cellValue, index) {
      if (cellValue === 1) {
        return 'Android'
      } else {
        return 'iOS'
      }
    },
    handleClickDialog() {
      this.campaignTasksDialog = true
      this.getData()
    },
    // 显示保存模板弹窗
    showSaveTemplateDialiog(row) {
      console.log(row);
      this.templateDialog = true
      this.sourceData = row.sourceData
    },
    submitTemplate() {
      this.$refs.templateForm.validate(async valid => {
        if (!valid) return
        await createTiktokCampaignTemplate({
          sourceData: this.sourceData,
          templateName: this.templateForm.name
        })
        this.$message.success('保存成功')
        this.templateDialog = false
      })

    },
    async getTemplateData() {
      this.loading = true
      const {data: res} = await getTiktokCampaignTemplateList(this.formatQueryform).finally(() => {
        this.loading = false
      })
      this.templateData = res.data
    },
    closeTemplateDialog() {
      this.$refs.templateForm.resetFields()
    },
    setCampaignTasksDialog(val) {
      this.campaignTasksDialog = val
      this.getData()
      this.activeName = 'second'
    },
    delTemplate(row) {
      console.log(row)
      this.$confirm('此操作将永久删除' + row.name + ', 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await removeTiktokCampaignTemplateList(row.id)
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      }).finally(() => {
        this.getTemplateData()
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.curd-table {
  .tab-header {
    font-size: 14px;
    margin-bottom: 15px;

    .tab-header-left {
      float: left;

      & > * {
        margin-right: 15px;
      }
    }

    .tab-header-right {
      float: right;
    }
  }

  .bottom-page {
    margin-top: 15px;

    .el-pagination {
      float: right;
    }
  }
}
</style>
